package com.wcfsy.wechat.wx.util.excel;

import java.io.InputStream;
import java.io.PushbackInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcelParseUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelParseUtil.class);

    public static List<List<String>> getExcelContent(InputStream in) throws Exception{

        Workbook wb = null;
        try {
            if (!in.markSupported()) {
                in = new PushbackInputStream(in, 8);
            }
            if (POIFSFileSystem.hasPOIFSHeader(in)) {
                wb = new HSSFWorkbook(in);
            }
            if (wb == null && POIXMLDocument.hasOOXMLHeader(in)) {
                wb = new XSSFWorkbook(OPCPackage.open(in));
            }
        } catch (Exception e) {
            LOGGER.error("ParseExcel found Exception: " + e.getMessage());
            throw new RuntimeException("您上传的excel不能解析，请下载模板导入数据!");
        }
        List<List<String>> result = new ArrayList<List<String>>();
        Sheet sheet1 = wb.getSheetAt(0);
        for (Row row : sheet1) {
            List<String> r = new ArrayList<String>();
            for (Cell cell : row) {
                String cellContent;
                try {
                    cellContent = cell.getStringCellValue().trim();
                    r.add(cellContent);
                } catch (IllegalStateException e) {
                    DecimalFormat df = new DecimalFormat("0");
                    cellContent = df.format(cell.getNumericCellValue());
                    r.add(cellContent);
                } catch (Exception e) {
                    LOGGER.error("Exception found in excel parseing:" + e.getMessage());
                    r.add("此处数据格式与模板不一致");
                }
            }
            result.add(r);
        }
        return result;
    }
}
